package netty.simple;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import netty.simple.netty.ServerHandler;

/**
 * @ClassName NettyServer
 * @Description TODO
 * @Author director吴
 * @Date 2022/1/18 13:14
 * @Version 1.0
 **/
public class NettyServer {

    public static void main(String[] args) {

        //两个线程组 group
        //两个线程组的线程个数  ==   默认 CPU 核心数 * 2
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        


        try {
        //创建服务器端的启动对象
        ServerBootstrap bootstrap = new ServerBootstrap();

        //链式设置
        bootstrap.group(bossGroup, workerGroup)                             //设置   两个线程组
                 .channel(NioServerSocketChannel.class)                     //使用 NioServerSocketChannel .作为通道实现
                 .option(ChannelOption.SO_BACKLOG, 128)               //设置  线程队列得到连接的个数
                 .childOption(ChannelOption.SO_KEEPALIVE,true )       //设置保持活动连接状态
                /**
                 *    .handler() api:    是给 bossGroup 添加处理器
                 *    .childHandler()  api:    是给 workerGroup 添加处理器
                 */
//                 .handler("handler")
                 .childHandler(new ChannelInitializer<SocketChannel>() {    //创建一个通道测试对象

                     //设置处理器
                     @Override
                     protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new ServerHandler());
                     }
                 });  //给workGroup 对应的管道设置处理器


        System.out.println("服务器准备就绪");



            //绑定端口  并且同步
            ChannelFuture channelFuture = bootstrap.bind(6668).sync();


            //给channeFutre注册监听器，监控我们关心的事件
            channelFuture.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (future.isSuccess()){

                        System.out.println("监听成功");
                    }else{
                        System.out.println("监听失败");
                    }

                }
            });



            //关闭通道
            channelFuture.channel().closeFuture().sync();

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }


    }
}
